<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>发布订阅模式</title>
</head>
<body>
  <script>
    // 事件触发器
    class EventEmitter {
      constructor () {
        this._event = {}
      }
      
      // 注册事件
      $on (eventType, handler) {
        // (this._event[eventType] || (this._event[eventType] = [])).push(handler)
        this._event[eventType] = this._event[eventType] || []
        this._event[eventType].push(handler)
      }

      // 触发事件
      $emit (eventType) {
        const payload = Array.prototype.slice.call(arguments, 1)
        // console.log(payload)
        let arr = this._event[eventType] || []

        for (let index = 0; index < arr.length; index++) {
          const handler = this._event[eventType][index]
          handler.call(this, payload)
        }
      }
    }

  var obj = new EventEmitter()
  obj.$on('hello',function (a, b) {
    console.log(a,b)
  })
  obj.$emit('hello',1,2)
  //取消订阅事件的回调必须是具名函数
  obj.$on('test',handler1 = function () {
    console.log('handler1')
  })
  obj.$on('test',handler2 = function () {
    console.log('handler2')
  })
  // obj.$off('test',handler1)
  obj.$emit('test')
  </script>
</body>
</html>